package com.naiterui.ehp.bs.ds.common.json;

import java.io.IOException;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import com.naiterui.ehp.bs.ds.modules.sys.utils.DictUtil;

import lombok.extern.slf4j.Slf4j;


/**
 * <pre>
 *   字典过滤
 * </pre>
 *
 * @author 王泽浩
 * @date 2019-02-19 14:14
 * @since 1.0.0
 */
@Slf4j
public class DictFieldSerializer extends StdSerializer<Object> implements ContextualSerializer {

    private static final long serialVersionUID = -6171864107747220506L;

    private String type;

    private String field;

    @SuppressWarnings("unused")
    public DictFieldSerializer() {
        super(Object.class);
    }

    private DictFieldSerializer(String field, String type) {
        super(Object.class);
        this.field = field;
        this.type = type;
    }

    @Override
    public JsonSerializer<?> createContextual(SerializerProvider prov, BeanProperty property) {
        Dict dict = property.getAnnotation(Dict.class);
        if (dict != null) {
            return new DictFieldSerializer(property.getName(), dict.type());
        }
        return null;
    }

    @Override
    public void serialize(Object value, JsonGenerator gen, SerializerProvider provider) throws IOException {
        gen.writeObject(value);
        if (value == null) {
            gen.writeStringField(this.field + "Describe", null);
        } else {
            String dictValue = DictUtil.getNameByTypeAndCode(this.type, value + "");
            gen.writeStringField(this.field + "Describe", dictValue);
        }
    }
}